package com.weixin.paleituo.view;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.weixin.paleituo.R;
import com.weixin.paleituo.activity.CreateOrderActivity;
import com.weixin.paleituo.activity.LoginActivity;
import com.weixin.paleituo.adapter.SelectGoodsRecycleAdapter;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.ActivityLifeCycleEvent;
import com.weixin.paleituo.bean.AddShopBean;
import com.weixin.paleituo.bean.GoodsSelectBean;
import com.weixin.paleituo.bean.GoodsSpecifBean;
import com.weixin.paleituo.bean.OrderGoods;
import com.weixin.paleituo.bean.PropertyListBean;
import com.weixin.paleituo.bean.SelectAttrBean;
import com.weixin.paleituo.bean.SpecificationListBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.eventbus.SelectGoodsEvent;
import com.weixin.paleituo.eventbus.UpdateShopCarNumber;
import com.weixin.paleituo.help.TextWatcherImp;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.http.RxHelper;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.LoadingDialogUtils;
import com.weixin.paleituo.util.LogUtils;
import com.weixin.paleituo.util.StringUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.subjects.PublishSubject;

/**
 * Author yichao
 * Time  2017/12/10 20:06
 * Dest  选择商品属性
 */

public class SelectGoodsAttriPopuWindow extends PopupWindow {

    private View rootView;
    private Context context;
    private PublishSubject<ActivityLifeCycleEvent> mLifecycleSubject;
    private RecyclerView mRecyclerView;
    private ImageView mIvDelete;
    private List<SpecificationListBean> mSpecificationList=new ArrayList<>();
    private SelectGoodsRecycleAdapter mSelectGoodsRecycleAdapter;
    private ImageView mIvicon;
    private TextView mTvSelectNumber;
    private TextView mTvSelectAttr;
    private TextView mTvMoney;
    private int mGoodsId;
    private Dialog mLoadingDialog;
    private TextView mTvSure;
    private String mLastName;
    private double mStorePrice;
    private int mNumber;
    private int mCustomized;
    private HeaderAndFooterWrapper mHeaderAndFooterWrapper;
    private View mFootView;
    private LinearLayout mLlcustomserviceRoot;
    private Button mButton ;
    private EditText mEditText;
    boolean   isvisible=false;
    private String TAG="SelectGoodsAttriPopuWindow";
    private  ArrayList<GoodsSpecifBean> mGoodsSpecifBeans=new ArrayList<>();
    private double mCoupon;
    private String mIconUrl;
    private String mGoodsName;
    private String mStoreId;
    private double mVipPrice;
    private boolean mIsvip;
    private String mIdList="";//选中的规格属性
    private ImageView mVipImageView;

    public SelectGoodsAttriPopuWindow(Context context, PublishSubject<ActivityLifeCycleEvent> lifecycleSubject) {
        super(context);
        this.context = context;
        mLifecycleSubject = lifecycleSubject;
        init();
    }
    private void init() {
        rootView = LayoutInflater.from(context).inflate(R.layout.select_goods_attr_popuwindow_layout, null);
        mIvicon=  rootView.findViewById(R.id.iv_icon_select_goods_attr_popuwindow_layout);
        mIvDelete  = rootView.findViewById(R.id.iv_delete_select_goods_attr_popuwindow_layout);
        mTvSelectNumber = rootView.findViewById(R.id.tv_select_number_select_goods_attr_popuwindow_layout);
        mTvSelectAttr = rootView.findViewById(R.id.tv_selected_attr_select_goods_attr_popuwindow_layout);
        mTvMoney = rootView.findViewById(R.id.tv_monety_select_goods_attr_popuwindow_layout);
        mTvSure = rootView.findViewById(R.id.tv_sure_select_goods_attr_popuwindow_layout);
        mVipImageView = rootView.findViewById(R.id.iv_vipicon_select_goods_attr_popuwindos_layout);
        mIvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        rootView.findViewById(R.id.view_select_goods_attr_popuwindow).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        mFootView = UIUtils.inflate(context, R.layout.layout_select_goods_attr_foot);

        mLlcustomserviceRoot = mFootView.findViewById(R.id.ll_customservice_root_layout_select_goods_attr_foot);
        mButton = mFootView.findViewById(R.id.rb_layout_select_goods_attr_foot);
        mEditText = mFootView.findViewById(R.id.et_custom_layout_select_goods_attr_foot);
        mButton.setSelected(false);

        mButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        if (!BaseApplication.isLoginSuccess){
            LoginActivity.startActivity(context,true);
            return;
        }

        if (!isvisible){
            isvisible=true;
            mEditText.setVisibility(View.VISIBLE);
            mButton.setSelected(true);

            mSelectGoodsRecycleAdapter.setVisible(true);
            //xianshi

        }else {
            isvisible=false;
            mButton.setSelected(false);
            mEditText.setVisibility(View.GONE);
            mSelectGoodsRecycleAdapter.setVisible(false);
            //关闭

        }
        setCustomshow();

    }
});

        mEditText.addTextChangedListener(new TextWatcherImp() {
            @Override
            public void afterTextChanged(Editable s) {
                String s1 = s.toString();
                setCustomshow();
            }
        });

        NumberButton numberButton=   mFootView.findViewById(R.id.number_button);
        numberButton.setBuyMax(200)
                .setInventory(1000)
                .setCurrentNumber(1)
                .setOnWarnListener(new NumberButton.OnWarnListener() {

                    @Override
                    public void onWarningForInventory(int inventory) {
                        ToastUtils.makeText("当前库存:" + inventory);
                    }
                    @Override
                    public void onWarningForBuyMax(int buyMax) {
                        ToastUtils.makeText("超过最大购买数:" + buyMax);
                    }

                    @Override
                    public void number(int number) {
                        mNumber = number;
                        mTvSelectNumber.setText("数量    " + number);

                    }
                });
        // TODO: 2016/5/17 设置动画
       // setAnimationStyle(R.style.dialog);

        // TODO: 2016/5/17 设置背景颜色
      setBackgroundDrawable(new ColorDrawable(0x90000000));
        // TODO: 2016/5/17 设置可以获取焦点
      setFocusable(true);
        // TODO: 2016/5/17 设置可以触摸弹出框以外的区域
      setOutsideTouchable(true);
        // TODO：更新popupwindow的状态
        setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        setContentView(rootView);
        mRecyclerView = rootView.findViewById(R.id.recycle_select_goods_attr_popuwindow_layout);
        mSelectGoodsRecycleAdapter = new SelectGoodsRecycleAdapter(context,mSpecificationList);
        mHeaderAndFooterWrapper = new HeaderAndFooterWrapper(mSelectGoodsRecycleAdapter);
        mHeaderAndFooterWrapper.addFootView(mFootView);
        //设置布局管理器
        mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
        //设置adapter
        mRecyclerView.setAdapter(mHeaderAndFooterWrapper);
        //设置Item增加、移除动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        //添加分割线
 /*   /*//*    mRecyclerView.addItemDecoration(new DividerItemDecoration(
                context, DividerItemDecoration.VERTICAL));*/
        mSelectGoodsRecycleAdapter.setSelectAttrListener(new SelectGoodsRecycleAdapter.SelectAttrListener() {




            @Override
            public void selectOnClick(String idList,  int selectPosition,  int position) {
                mIdList = idList;
                mGoodsSpecifBeans.remove(position);
                SpecificationListBean specificationListBean = mSpecificationList.get(position);

                String name = specificationListBean.getName();
                PropertyListBean propertyListBean = specificationListBean.getPropertyList().get(selectPosition);
                int id = propertyListBean.getId();
                String value = propertyListBean.getValue();
                GoodsSpecifBean goodsSpecifBean=new GoodsSpecifBean();
                goodsSpecifBean.setTypeName(name);
                goodsSpecifBean.setId(id);
                goodsSpecifBean.setName(value);
                mGoodsSpecifBeans.add(position,goodsSpecifBean);

                LogUtils.i(TAG,"selectPostiont::"+selectPosition +"_____position"+position);

                Observable observable = ApiUtils.getApi().getGoodsAttr(mGoodsId, idList, BaseApplication.getToken(),BaseApplication.getUserId())
                        .compose(RxHelper.getObservaleTransformer()).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        if (mLoadingDialog == null) {

                            mLoadingDialog = LoadingDialogUtils.createLoadingDialog(context, "");
                        }
                        LoadingDialogUtils.show(mLoadingDialog);

                    }
                }).subscribeOn(AndroidSchedulers.mainThread());

                HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<SelectAttrBean>(context) {
                    @Override
                    protected void _onNext(StatusCode<SelectAttrBean> selectAttrBeanStatusCode) {
                        LoadingDialogUtils.closeDialog(mLoadingDialog);
                        SelectAttrBean data = selectAttrBeanStatusCode.getData();
                        if (selectAttrBeanStatusCode.isFlag()&&data!=null){
                            mTvSure.setEnabled(true);
                            mTvSure.setFocusable(true);
                            mLastName = data.getLastName();
                            mStorePrice = data.getStorePrice();
                            mCustomized = data.getCustomized();
                            mVipPrice = data.getSpecialSales();
                            mCoupon = data.getCoupon();
                            UIUtils.loadImageView(context,data.getSummaryList(),mIvicon);

                          //  mTvSelectNumber.setText("数量"+data.getSelectNumber());
                            String editConte = mEditText.getText().toString();
                            mTvSelectAttr.setTextColor(UIUtils.getColor(R.color.c_383838));
                            mTvSelectAttr.setText(StringUtils.isEmpty(mLastName)?"":mLastName);
                            if (mIsvip&&!isvisible){
                                mVipImageView.setVisibility(View.VISIBLE);
                                mTvMoney.setTextColor(UIUtils.getColor(R.color.c_29CE7E));
                                mTvMoney.setText("￥"+UIUtils.getMoney(mVipPrice));
                            }else {
                                mTvMoney.setText("￥"+UIUtils.getMoney(mStorePrice));
                                mTvMoney.setTextColor(UIUtils.getColor(R.color.c_ed5240));
                                mVipImageView.setVisibility(View.INVISIBLE);
                            }
                        }else {
                            mTvSure.setEnabled(false);
                            mTvSure.setFocusable(false);
                            ToastUtils.makeText(selectAttrBeanStatusCode.getDetailMsg());
                        }
                    }

                    @Override
                    protected void _onError(String message) {
                        LoadingDialogUtils.closeDialog(mLoadingDialog);
                        ToastUtils.makeText(message);
                        mTvSure.setEnabled(false);
                        mTvSure.setFocusable(false);

                    }
                },"",mLifecycleSubject,false,true);


            }
        });
/*确定*/
        mTvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //确定
              //  dismiss();
             //   EventBus.getDefault().post(new SelectAttrDissEvent(mLastName,mStorePrice,mNumber));
    if (!BaseApplication.isLoginSuccess){
    LoginActivity.startActivity(context,true);
        return;
}


            String etContet = mEditText.getText().toString();

                SelectGoodsEvent selectGoodsEvent=new SelectGoodsEvent();
                selectGoodsEvent.setPrice(mStorePrice);
                selectGoodsEvent.setVipPrice(mVipPrice);
                selectGoodsEvent.setIsvip(mIsvip);
                selectGoodsEvent.setSelectNum(mNumber);
                selectGoodsEvent.setSelectInfo(mLastName);
                EventBus.getDefault().post(selectGoodsEvent);


    if (isvisible){
        //定制
        if (StringUtils.isEmpty(etContet)){
            ToastUtils.makeText("请输入您的定制服务需求");
            return;
        }
        ArrayList<OrderGoods> orderGoodsList=new ArrayList<>();
        OrderGoods orderGoods=new OrderGoods();
        orderGoods.setGoodsName(mGoodsName);
        orderGoods.setCount(mNumber);
        orderGoods.setId(mGoodsId);
        orderGoods.setListUrl(mIconUrl);
        orderGoods.setStoreId(Integer.valueOf(mStoreId));
        orderGoods.setPrice(Double.toString(mStorePrice));
        orderGoods.setVip(mIsvip);
        orderGoods.setSpecialSales(mVipPrice+"");
        orderGoods.setGoodsSpecsList(mGoodsSpecifBeans);
        orderGoods.setCouponMoney(mCoupon);
        orderGoods.setGoodsSpecsInfo(mLastName);
        orderGoodsList.add(orderGoods);
        Intent intent = CreateOrderActivity.call2CreateOrder(context, etContet, orderGoodsList);
        context.startActivity(intent);
        dismiss();
    }else {
        //非定制加入购物车
        Observable addShopCarObservable = ApiUtils.getApi().addShopCar(mGoodsId, mNumber, BaseApplication.getUserId(), mIdList)
                .compose(RxHelper.getObservaleTransformer()).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        if (mLoadingDialog == null) {

                            mLoadingDialog = LoadingDialogUtils.createLoadingDialog(context, "");
                        }
                        LoadingDialogUtils.show(mLoadingDialog);

                    }
                }).subscribeOn(AndroidSchedulers.mainThread());

        HttpUtil.getInstance().toSubscribe(addShopCarObservable, new ProgressSubscriber<AddShopBean>(context) {

            @Override
            protected void _onNext(StatusCode<AddShopBean> addShopBeanStatusCode) {
                LoadingDialogUtils.closeDialog(mLoadingDialog);

                AddShopBean addShopBean = addShopBeanStatusCode.getData();

                if (addShopBeanStatusCode.isFlag()&&addShopBean!=null){
                    ShopCarToastView shopCarToastView= new ShopCarToastView(context);
                    shopCarToastView.setDuration(Toast.LENGTH_LONG);
                    shopCarToastView.show();
                    dismiss();
                    int cart_num = addShopBean.getCart_num();

                    EventBus.getDefault().post(new UpdateShopCarNumber(cart_num));

                }else {
                    ShopCarToastView shopCarToastView= new ShopCarToastView(context);
                    shopCarToastView.setIcon(R.mipmap.address_error);
                    shopCarToastView.setText("加入购物车失败");
                    shopCarToastView.setDuration(Toast.LENGTH_LONG);
                    shopCarToastView.show();
                }


            }

            @Override
            protected void _onError(String message) {
                LoadingDialogUtils.closeDialog(mLoadingDialog);

                ShopCarToastView shopCarToastView= new ShopCarToastView(context);
                shopCarToastView.setIcon(R.mipmap.address_error);
                shopCarToastView.setText("加入购物车失败");
                shopCarToastView.setDuration(Toast.LENGTH_LONG);
                shopCarToastView.show();


            }
        },"", mLifecycleSubject,false,true);



    }
              //

            }
        });
    }

    /**
     * 显示定制
     */
    private  void setCustomshow() {
        if (isvisible){
            mTvSure.setText("去定制");
            mTvSelectAttr.setText("私人订制");
            mTvMoney.setText("待定");
            mVipImageView.setVisibility(View.INVISIBLE);
            mTvMoney.setTextColor(UIUtils.getColor(R.color.c_ed5240));
            mTvSelectAttr.setTextColor(UIUtils.getColor(R.color.c_383838));
        }else {
            mTvSelectAttr.setTextColor(UIUtils.getColor(R.color.c_383838));
            if (mIsvip){
                mVipImageView.setVisibility(View.VISIBLE);
                mTvMoney.setTextColor(UIUtils.getColor(R.color.c_29CE7E));
                mTvMoney.setText("￥"+ UIUtils.getMoney(mVipPrice));
            }else {
                mTvMoney.setText("￥"+ UIUtils.getMoney(mStorePrice));
                mTvMoney.setTextColor(UIUtils.getColor(R.color.c_ed5240));
                mVipImageView.setVisibility(View.INVISIBLE);
            }
            mTvSure.setText("确定");
            mTvSelectAttr.setText(StringUtils.isEmpty(mLastName)?"" :mLastName);
        }
    }

    @Override
    public void showAsDropDown(View anchor) {
        if(Build.VERSION.SDK_INT >= 24){
            Rect visibleFrame = new Rect();
            anchor.getGlobalVisibleRect(visibleFrame);
            int height = anchor.getResources().getDisplayMetrics().heightPixels - visibleFrame.bottom;
            setHeight(height);
        }
        super.showAsDropDown(anchor);
    }

    @Override
    public void showAsDropDown(View anchor, int xoff, int yoff) {
        if(Build.VERSION.SDK_INT >= 24){
            Rect visibleFrame = new Rect();
            anchor.getGlobalVisibleRect(visibleFrame);
            int height = anchor.getResources().getDisplayMetrics().heightPixels - visibleFrame.bottom;
            setHeight(height);
        }
        super.showAsDropDown(anchor, xoff, yoff);
    }
    /**
     *
     * @param goodsSelectBean
     * @param goodsId
     */
    public void setGoodsSelectBean(GoodsSelectBean goodsSelectBean, int goodsId) {
        mGoodsId =goodsId;
        mIconUrl = goodsSelectBean.getSummary();
        mLastName=goodsSelectBean.getSelectedLastName();
        mStorePrice=goodsSelectBean.getStorePrice();
        mNumber=goodsSelectBean.getSelectNumber();
        mCoupon=goodsSelectBean.getCoupon();
        mGoodsName = goodsSelectBean.getGoodsName();
        mStoreId = goodsSelectBean.getStoreId();
        mVipPrice = goodsSelectBean.getVipPrice();
        mIsvip = goodsSelectBean.isVip();
        Glide.with(context).load(mIconUrl).into(mIvicon);
        mTvSelectNumber.setText("数量    "+goodsSelectBean.getSelectNumber());
        mTvSelectAttr.setText(StringUtils.isEmpty(mLastName)?"":mLastName);

        mSelectGoodsRecycleAdapter.notifyDataSetChanged();
if (mIsvip){
    mVipImageView.setVisibility(View.VISIBLE);
    mTvMoney.setTextColor(UIUtils.getColor(R.color.c_29CE7E));
    mTvMoney.setText("￥"+UIUtils.getMoney(goodsSelectBean.getVipPrice()));
}else {
    mTvMoney.setText("￥"+UIUtils.getMoney(goodsSelectBean.getStorePrice()));
    mTvMoney.setTextColor(UIUtils.getColor(R.color.c_ed5240));
    mVipImageView.setVisibility(View.INVISIBLE);

}


    }
    /**
     * 设置属性
     * @param specificationList
     */
    public void setList(List<SpecificationListBean> specificationList) {
        mSpecificationList.clear();
        mSpecificationList.addAll(specificationList);

        if (specificationList!=null&& specificationList.size()>0){
            for (SpecificationListBean specificationListBean:specificationList){
                String name = specificationListBean.getName();
                List<PropertyListBean> propertyList = specificationListBean.getPropertyList();
                if (propertyList!=null &&propertyList.size()>0){
                    PropertyListBean propertyListBean = propertyList.get(0);
                    int id = propertyListBean.getId();
                    mIdList=mIdList+id+"_";
                    String value = propertyListBean.getValue();
                    GoodsSpecifBean goodsSpecifBean=new GoodsSpecifBean();
                    goodsSpecifBean.setTypeName(name);
                    goodsSpecifBean.setId(id);
                    goodsSpecifBean.setName(value);
                    mGoodsSpecifBeans.add(goodsSpecifBean);
                }



            }
        }

        mSelectGoodsRecycleAdapter.setSelectIdArr();
        mSelectGoodsRecycleAdapter.notifyDataSetChanged();
    }

    /**
     * 是否定制
     * @param customized  制1支持2不支持
     */
    public void setCustomized(int customized) {
        if (customized==1){
            mLlcustomserviceRoot.setVisibility(View.VISIBLE);
        }else {
            mLlcustomserviceRoot.setVisibility(View.GONE);
        }

        mCustomized = customized;
    }
}
